package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.constant.SendMessageConstantModel;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.utils.TengXunMessageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")

public class OrderController {
    @Reference
    private OrderService orderService;
    @Autowired
    private JedisPool jedisPool;
    /**
     * /order/submit.do",this.orderInfo
     * telephone+ RedisMessageConstant.SENDTYPE_ORDER
     */
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map){
//      1.查看验证码是否正确
//           查看redis与用户输入是否正确
         String verCode= (String) map.get("validateCode");
         String telephone = (String) map.get("telephone");
        String redisVercode = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        if (!(verCode.equals(redisVercode)) || verCode==null){
            // 如果不同或者超时间,则返回
          return  new Result(false,MessageConstant.VALIDATECODE_ERROR);
        }
//      2.调用预约服务,能否成功
        Result result=null;
        try {
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            result=orderService.submit(map);
        }catch (Exception e){
            return  result;
        }
        if (result.isFlag()){
            //        预约成功则发送短信--发送短信
            String date= (String) map.get("orderDate");
            String[] dates=new String[]{date};
            TengXunMessageUtils.sendMessage(dates, SendMessageConstantModel.ORDER_SUCCESS,telephone);
            }
            return result;
    }
    /**
     *    order/findById.do?id=" + id
     */
      @RequestMapping("/findById")
      public Result findById(Integer id){
          try{
              Map map=orderService.findById(id);
              return new Result(true,MessageConstant.QUERY_ORDER_FAIL,map);
          }catch (Exception e){
              return  new Result(false,MessageConstant.QUERY_ORDER_FAIL);
          }
      }
}
